package com.shuimin.group.service;


import com.shuimin.group.logic.TokenLogic;
import com.shuimin.group.util.HttpUtil;
import com.shuimin.group.util.XMLUtil;
import io.netty.util.CharsetUtil;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.jdom.JDOMException;
import pond.common.*;
import pond.web.Response;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class WeixinService {
    public  static final String TOKEN = "xknjcwiefsdfpasdjiaosu";

    private static final String APP_ID = "wxd53ebb481f8f362b";
    private static final String APP_SECRET = "3225b3e2eae8469d5a394ef54c7b28db";

    private static final String SUB_APP_ID = "wx74699bac4fafa5b5";
    private static final String SUB_APP_SECRET = "ad848030468754bc9da991bde3070daf";
    private static final String APP_GRANT_TYPE = "authorization_code";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    private static final String TEMPLATE_MSG_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    private static final String USER_INFO_URL =    "https://api.weixin.qq.com/cgi-bin/user/info?access_token=";
    private static final String JS_CODE2_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=";

    public static String GET_Code2Session_URL(String code) {
        S._assertNotNull(code);
        return   JS_CODE2_SESSION_URL + SUB_APP_ID
                + "&secret=" + SUB_APP_SECRET
                + "&js_code=" + code
                + "&grant_type=" + APP_GRANT_TYPE;
    }
    public static Map<String, String> getAppSessionByCode(String code) throws IOException {
        Map<String, String> map = new HashMap<>();
        String url = GET_Code2Session_URL(code);
        S.echo(url);
        HTTP.get(url, resp -> {
            HttpEntity entity = resp.getEntity();
            if (entity == null) {
                throw new RuntimeException("404");
            }
            ContentType ct = ContentType.getOrDefault(entity);
            try {
                StringBuffer out = new StringBuffer();
                String in = S.stream.readFully(entity.getContent(), CharsetUtil.UTF_8);
                S.echo(S.dump(JSON.parse(in)));
                Map<String, String> returnMap = JSON.parse(in);
                map.putAll(returnMap);
            } catch (Exception e) {
                throw new RuntimeException("");
            }

        });
        return map;
    }

    public static Map<String,Object> getUser(String openid) throws IOException {
        S._assertNotNull(openid);
        Map<String,Object> map = new HashMap<>();
        String url = USER_INFO_URL + getToken() + "&openid=" + openid;
        HTTP.get(url, resp -> {
            try {
                String json_utf8 = STREAM.readFully(resp.getEntity().getContent(), CharsetUtil.UTF_8);
                S.echo("get str:"+ json_utf8 );
                map.putAll(JSON.parse(json_utf8));
            } catch (IOException e) {
                S.echo(e.getMessage(), e);
            }
        });
        return map;
    }
    public static String getToken()
    {
        return TokenLogic.getToken(ACCESS_TOKEN_URL,APP_ID,APP_SECRET);
    }

    public static Map<String, String> parseXml(InputStream is) throws IOException, JDOMException {
        return XMLUtil.doXMLParse(S.stream.readFully(is, CharsetUtil.UTF_8));
    }
    public static void out(Map<String, Object> params, Response resp) {
        try {
            STREAM.pipe(XMLUtil.fromString(XMLUtil.getXmlBody(params)), resp.out());
            resp.send(200);
        } catch (IOException e) {
            e.printStackTrace();
            resp.send(500);
        }
    }

    /* 0 为成功，其他为错误码 https://mp.weixin.qq.com/debug/cgi-bin/readtmpl?t=tmplmsg/faq_tmpl*/
    public static int sendTemplateMsg(String touser, String template_id, String url, Map<String,Map<String,String>> miniprogram, Map<String,Map<String,String>> data)
    {
        Map<String, Object> map = new HashMap<>();
        S._assertNotNull(touser,template_id,data);
        map.put("touser", touser);
        map.put("template_id", template_id);
        if (STRING.isBlank(url))
        {
            map.put("url","");
        }
        else
        {
            map.put("url",url);
        }
        if (null != miniprogram && miniprogram.size() >0)
        {
            map.put("miniprogram", miniprogram) ;
        }
        map.put("data", data);
        String u = TEMPLATE_MSG_URL+getToken();
        S.echo(JSON.stringify(map));
        String result= HttpUtil.sendPost(u,JSON.stringify(map));
        S.echo(result);
        Map<String,Object> ret = JSON.parse(result);
        /*{
           "errcode":0,
           "errmsg":"ok",
           "msgid":200228332
        }*/
        return (Integer)ret.get("errcode");
    }
}
